// 文件扫描工具
export class FileScanner {
  constructor() {
    this.supportedTextureFormats = ['.jpg', '.jpeg', '.png', '.webp', '.svg', '.bmp', '.gif']
    this.supportedModelFormats = ['.gltf', '.glb', '.obj', '.fbx', '.dae', '.ply', '.stl']
    
    // 常见的文件名模式，用于自动发现
    this.commonTextureNames = [
      'checkerboard', 'brick', 'wood', 'metal', 'fabric', 'stone', 'concrete',
      'grass', 'sand', 'water', 'marble', 'leather', 'plastic', 'glass',
      'diffuse', 'albedo', 'normal', 'roughness', 'metallic', 'height', 'ao'
    ]
    
    this.commonModelNames = [
      'cube', 'sphere', 'cylinder', 'plane', 'torus', 'cone',
      'monkey', 'suzanne', 'teapot', 'bunny', 'dragon', 'car', 'house'
    ]
    
    // 缓存已发现的文件
    this.discoveredTextures = []
    this.discoveredModels = []
    this.lastScanTime = 0
    this.scanCacheTimeout = 30000 // 30秒缓存
  }
 
  // 自动发现文件夹中的文件
  async discoverFiles(basePath, fileNames, supportedFormats) {
    const discoveredFiles = []
    
    // 尝试所有可能的文件名和格式组合
    for (const name of fileNames) {
      for (const format of supportedFormats) {
        const filename = `${name}${format}`
        const fullPath = `${basePath}/${filename}`
        
        try {
          const exists = await this.checkFileExists(fullPath)
          if (exists) {
            discoveredFiles.push({
              name: filename,
              path: fullPath,
              extension: format,
              nameWithoutExt: name,
              displayName: this.getDisplayName(filename),
              type: this.getFileType(format)
            })
          }
        } catch (error) {
          // 忽略单个文件检查失败
          continue
        }
      }
    }
    
    return discoveredFiles
  }

  // 获取文件类型
  getFileType(extension) {
    if (this.supportedTextureFormats.includes(extension)) {
      return 'texture'
    } else if (this.supportedModelFormats.includes(extension)) {
      return 'model'
    }
    return 'unknown'
  }

  // 检查是否需要重新扫描
  shouldRescan() {
    const now = Date.now()
    return (now - this.lastScanTime) > this.scanCacheTimeout
  }
  async checkFileExists(path) {
    try {
      const response = await fetch(path, { method: 'HEAD' })
      return response.ok
    } catch (error) {
      return false
    }
  }

  // 扫描纹理文件（使用缓存和自动发现）
  async scanTextures(basePath = '/textures', forceRescan = false) {
    // 如果有缓存且不需要强制重新扫描，返回缓存结果
    if (!forceRescan && this.discoveredTextures.length > 0 && !this.shouldRescan()) {
      return this.discoveredTextures
    }
    
    console.log('正在扫描纹理文件...')
    
    // 自动发现纹理文件
    const discoveredTextures = await this.discoverFiles(
      basePath, 
      this.commonTextureNames, 
      this.supportedTextureFormats
    )
    
    // 更新缓存
    this.discoveredTextures = discoveredTextures
    this.lastScanTime = Date.now()
    
    console.log(`发现 ${discoveredTextures.length} 个纹理文件:`, discoveredTextures.map(t => t.name))
    
    return discoveredTextures
  }

  // 扫描模型文件（使用缓存和自动发现）
  async scanModels(basePath = '/models', forceRescan = false) {
    // 如果有缓存且不需要强制重新扫描，返回缓存结果
    if (!forceRescan && this.discoveredModels.length > 0 && !this.shouldRescan()) {
      return this.discoveredModels
    }
    
    console.log('正在扫描模型文件...')
    
    // 自动发现模型文件
    const discoveredModels = await this.discoverFiles(
      basePath, 
      this.commonModelNames, 
      this.supportedModelFormats
    )
    
    // 更新缓存
    this.discoveredModels = discoveredModels
    this.lastScanTime = Date.now()
    
    console.log(`发现 ${discoveredModels.length} 个模型文件:`, discoveredModels.map(m => m.name))
    
    return discoveredModels
  }

  // 添加新的纹理文件名到搜索列表
  addKnownTexture(filename) {
    const nameWithoutExt = this.getFileNameWithoutExtension(filename)
    if (!this.commonTextureNames.includes(nameWithoutExt) && this.isTextureFile(filename)) {
      this.commonTextureNames.push(nameWithoutExt)
      // 清除缓存以触发重新扫描
      this.discoveredTextures = []
      console.log(`添加新纹理文件名: ${nameWithoutExt}`)
    }
  }

  // 添加新的模型文件名到搜索列表
  addKnownModel(filename) {
    const nameWithoutExt = this.getFileNameWithoutExtension(filename)
    if (!this.commonModelNames.includes(nameWithoutExt) && this.isModelFile(filename)) {
      this.commonModelNames.push(nameWithoutExt)
      // 清除缓存以触发重新扫描
      this.discoveredModels = []
      console.log(`添加新模型文件名: ${nameWithoutExt}`)
    }
  }

  // 强制重新扫描所有文件
  async forceRescan() {
    console.log('强制重新扫描所有文件...')
    this.discoveredTextures = []
    this.discoveredModels = []
    this.lastScanTime = 0
    
    const [textures, models] = await Promise.all([
      this.scanTextures('/textures', true),
      this.scanModels('/models', true)
    ])
    
    return { textures, models }
  }

  // 检查文件类型
  isTextureFile(filename) {
    const ext = this.getFileExtension(filename)
    return this.supportedTextureFormats.includes(ext)
  }

  isModelFile(filename) {
    const ext = this.getFileExtension(filename)
    return this.supportedModelFormats.includes(ext)
  }

  getFileExtension(filename) {
    return filename.toLowerCase().substring(filename.lastIndexOf('.'))
  }

  // 获取文件名（不含扩展名）
  getFileNameWithoutExtension(filename) {
    return filename.substring(0, filename.lastIndexOf('.'))
  }

  // 获取显示名称
  getDisplayName(filename) {
    const nameWithoutExt = this.getFileNameWithoutExtension(filename)
    // 将下划线和连字符替换为空格，并首字母大写
    return nameWithoutExt
      .replace(/[_-]/g, ' ')
      .replace(/\b\w/g, l => l.toUpperCase())
  }

  // 按类型过滤文件（增强版）
  filterByType(files, type, subType = null) {
    let filtered = []
    
    switch (type) {
      case 'texture':
        filtered = files.filter(file => this.isTextureFile(file.name))
        break
      case 'model':
        filtered = files.filter(file => this.isModelFile(file.name))
        break
      case 'all':
      default:
        filtered = files
        break
    }
    
    // 子类型过滤
    if (subType && filtered.length > 0) {
      switch (subType) {
        case 'svg':
          filtered = filtered.filter(file => file.extension === '.svg')
          break
        case 'raster':
          filtered = filtered.filter(file => 
            ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.gif'].includes(file.extension)
          )
          break
        case 'gltf':
          filtered = filtered.filter(file => 
            ['.gltf', '.glb'].includes(file.extension)
          )
          break
        case 'obj':
          filtered = filtered.filter(file => file.extension === '.obj')
          break
        case 'fbx':
          filtered = filtered.filter(file => file.extension === '.fbx')
          break
      }
    }
    
    return filtered
  }

  // 按名称搜索文件
  searchByName(files, searchTerm) {
    if (!searchTerm || searchTerm.trim() === '') {
      return files
    }
    
    const term = searchTerm.toLowerCase()
    return files.filter(file => 
      file.name.toLowerCase().includes(term) ||
      file.nameWithoutExt.toLowerCase().includes(term) ||
      file.displayName.toLowerCase().includes(term)
    )
  }

  // 获取文件统计信息
  getFileStats(files) {
    const stats = {
      total: files.length,
      byType: {},
      byExtension: {}
    }
    
    files.forEach(file => {
      // 按类型统计
      const type = file.type || this.getFileType(file.extension)
      stats.byType[type] = (stats.byType[type] || 0) + 1
      
      // 按扩展名统计
      stats.byExtension[file.extension] = (stats.byExtension[file.extension] || 0) + 1
    })
    
    return stats
  }

  // 获取支持的文件格式信息
  getSupportedFormats() {
    return {
      textures: this.supportedTextureFormats,
      models: this.supportedModelFormats
    }
  }
}